<!--
 * @Author: ErCHen
 * @Date: 2021-12-23 12:27:35
 * @LastEditTime: 2022-03-22 15:36:34
-->

<template>
  <div ref="editor" id="VEditor"></div>
</template>

<script lang="ts">
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { IMAGE_URL, CDN } from '@/utils/netConf'
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'
import { checkToken } from '@/utils/check'

export default defineComponent({
  name: 'VueEditor',
  props: {
    options: {
      type: Object,
      required: false
    },
    modelValue: {
      type: String,
      default: '',
      required: false
    },
    placeholder: {
      type: String,
      default: '开始书写吧',
      required: false
    }
  },
  setup (props) {
    const editor = ref<HTMLElement | string>('VEditor')
    let instance: Vditor | null = null
    onMounted(() => {
      instance = new Vditor(editor.value, {
        value: props.modelValue,
        placeholder: props.placeholder,
        cache: { enable: false },
        cdn: CDN,
        toolbar: [
          'headings',
          'bold',
          'italic',
          'strike',
          'link',
          '|',
          'list',
          'ordered-list',
          'check',
          'outdent',
          'indent',
          '|',
          'quote',
          'line',
          'code',
          'inline-code',
          'insert-before',
          'insert-after',
          '|',
          'upload',
          'table',
          'edit-mode',
          '|',
          {
            name: 'more',
            toolbar: [
              'both',
              'export',
              'outline',
              'preview'
            ]
          }
        ],
        theme: 'classic',
        upload: {
          url: IMAGE_URL + '/image',
          accept: 'image/*',
          max: 5 * 1024 * 1024,
          multiple: false,
          headers: {
            Authorization: checkToken()
          },
          error: () => {
            window.alert('上传图片失败')
            // console.log(msg)
          }
        },
        preview: {
          theme: {
            path: CDN + '/dist/css/content-theme',
            current: 'classic'
          }
        }
      })
    })

    onBeforeUnmount(() => {
      if (instance !== null) {
        instance.destroy()
      }
    })

    // watch(
    //   () => props.modelValue,
    //   (content) => {
    //     // console.log('VueEditor:' + content)
    //     if (instance) {
    //       instance.setValue(content)
    //     }
    //   }
    // )

    const getEditorValue = (): string => {
      if (instance !== null) {
        return instance.getValue()
      }
      return ''
    }

    const setEditorValue = (value: string) => {
      if (instance !== null) {
        instance.setValue(value)
      }
    }
    return { editor, getEditorValue, setEditorValue }
  }
})
</script>

<style scoped>
  #VEditor {
    margin-top: 25px;
    /*max-width: 1300px;*/
  }
</style>
